﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

namespace IntegratedOnBordDebug.UDPCore
{
    public class BroadcastHelper
    {
        private readonly bool _isEncript;
        private readonly string _passPhrase;
        private readonly int _port;
        private UdpHelper _listener;
        private Queue<string> _received;
        private UdpHelper _talker;

        public BroadcastHelper(int port)
            : this(port, string.Empty) {
        }

        public BroadcastHelper(int port, string passPhrase) {
            _port = port;
            _isEncript = !string.IsNullOrEmpty(passPhrase);
            _passPhrase = passPhrase;
        }

        public Queue<string> Received {
            get {
                if (_listener == null) {
                    var udp = new UdpClient(_port);
                    var remoteEP = new IPEndPoint(IPAddress.Broadcast, 0);
                    _received = new Queue<string>();
                    _listener = new UdpHelper(udp, remoteEP);
                    Debug.Print("Listener initialized");
                }

                while (_listener.Received.Count > 0)
                    _received.Enqueue(_isEncript ? EncryptHelper.DecryptString(_listener.Received.Dequeue(), _passPhrase) : _listener.Received.Dequeue());

                return _received;
            }
        }

        public void Send(string s) {
            if (_talker == null) {
                var udp = new UdpClient();
                var remoteEP = new IPEndPoint(IPAddress.Broadcast, _port);
                _talker = new UdpHelper(udp, remoteEP);
                Debug.Print("Talker initialized");
            }

            _talker.Send(_isEncript ? EncryptHelper.EncryptString(s, _passPhrase) : s);
        }
    }
}